package com.work.daily.stream;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * Stream 的归约(reduce)
 *
 * @author Shengkang.Mo
 * @create 2020-11-26 16:41
 * 归约，也称缩减，顾名思义，是把一个流缩减成一个值，能实现对集合求和、求乘积和求最值操作。
 */
public class Stream_6_1 {
    public static void main(String[] args) {
        //求Integer集合的元素之和、乘积和最大值。
        List<Integer> list = Arrays.asList(1, 3, 2, 8, 11, 4);

        //求和方式1
        Optional<Integer> sum = list.stream().reduce((x, y) -> x + y);

        //求和方式2
        Optional<Integer> sum2 = list.stream().reduce(Integer::sum);

        //求和方式3
        Integer sum3 = list.stream().reduce(0, Integer::sum);

        //求乘积
        Optional<Integer> product = list.stream().reduce((x, y) -> x * y);

        //求最大值1
        Optional<Integer> max = list.stream().reduce((x, y) -> x > y ? x : y);

        //求最大值2
        Integer max2 = list.stream().reduce(1, Integer::max);

        System.out.println("list求和：" + sum.get() + "," + sum2.get() + "," + sum3);
        System.out.println("list求乘积：" + product.get());
        System.out.println("list求最大值：" + max.get() + "," + max2);

    }
}
